package com.bailiban.aigou.dao.impl;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;

import com.bailiban.aigou.dao.UserDao;
import com.bailiban.aigou.entity.User;
import com.bailiban.aigou.utils.PageModel;

@Repository
public class UseDaoImpl implements UserDao {

	@Resource
	private SessionFactory sessionFactory;
	
	public User getUserByName(String username) {
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery("from User where username = :name");
		query.setParameter("name", username);
		List<User> list = query.list();
		
		if (list==null || list.size()<=0) {
			return null;
		}
		return list.get(0);
	}

	@Override
	public PageModel<User> getAdminUser(int pageNo, int pageSize) {
		PageModel<User> pageModel = new PageModel<User>();
		pageModel.setPageNo(pageNo);
		pageModel.setPageSize(pageSize);
		
		Session session = sessionFactory.getCurrentSession();
		
		Criteria criteria = session.createCriteria(User.class);
		criteria.setFirstResult((pageNo-1)*pageSize);
		criteria.setMaxResults(pageSize);
		
		List<User> list = criteria.list();
		pageModel.setList(list);
		return pageModel;
	}

	@Override
	public void save(User user) {
		sessionFactory.getCurrentSession().save(user);
	}

	@Override
	public int getAdminUserCount() {
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery("select count(id) from User");
		List<Long> list = query.list();
		return list.get(0).intValue();
	}

}
